/*
 * @(#)ProviderSupport.java	1.0 2000/12/14
 *
 * Copyright 2000 Thomas Barnekow. All Rights Reserved.
 *
 * This software is the proprietary information of Thomas Barnekow.
 * Use is subject to license terms.
 */

package tb.provider;

import java.util.*;
import tb.util.*;

/**
 * A delegate that can be used to implement service providers
 */
public class ProviderSupport {

	private Map m_services = new HashMap();

	private Provider m_provider;

	/**
	 * Constructor.
   *
	 * @param provider	The client <i>Provider</i>.
	 */
	public ProviderSupport(Provider provider) {
		m_provider = provider;
	}

  /**
   * Get the set of entities that the given service is provided for.
   *
   * @param service individual service element or compound service
   */
	protected Set getEntitiesByService(QualifiedName service) {
		Set set = (Set) m_services.get(service);
		if (set == null) {
			set = new HashSet();
			m_services.put(service, set);
		}
		return set;
	}

	/*
	 * Provider operations
	 */

  /**
   * @see Provider#provide
   */
	public void provide(QualifiedName service, QualifiedName entity) {
		checkParams(service, entity);
		getEntitiesByService(service).add(entity);
    ProviderRegistry.registerProvider(service, m_provider);
	}

  /**
   * @see Provider#isProvider
   */
	public boolean isProvider(QualifiedName service, QualifiedName entity) {
		if (service == null || service.nameComponents() == 0 ||
				entity == null || entity.nameComponents() == 0)
		{
			return false;
		} else {
			return getEntitiesByService(service).contains(entity) ||
				isProvider(service.getNamespaceName(), entity) ||
				isProvider(service, entity.getNamespaceName());
		}
	}

	/*
	 * Utilities
	 */

  /**
   * Check to see if the service and entity values are valid non-null and non-empty
   * qualified names.
   */
	public void checkParams(QualifiedName service, QualifiedName entity) {
		if (service == null || service.nameComponents() == 0 ||
				entity == null || entity.nameComponents() == 0)
		{
			throw new IllegalArgumentException("Names must not be null or empty");
		}
	}
}
